<template>
    <a-layout id="components-layout-demo-side" style="min-height: 100vh;background-color: #fff;">
        <!--侧边栏部分-->
        <a-layout-sider style="background: #fff; osition: relative;" v-model="collapsed">
            <!--侧边栏关闭按钮-->
            <div class="aside_close" @click="changeCollapse">
                <i v-if="!collapsed"><img src="@/assets/icons/redis/u795_1.png"></i>
            </div>
            <!--侧边栏标题-->
            <div class="header">
                <div class="header-left">
                    <h6>Redis列表</h6>
                </div>
                <div>
                    <a-icon v-show="!collapsed" type="plus" class="header-button" @click="createLink()"></a-icon>
                </div>
                <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
                    style="width: 180px" v-show="!collapsed">
                    <line x1="20" y1="0" x2="200" y2="0" style="stroke:#f2f2f2;stroke-width:1;" />
                </svg>
            </div>
            <div :style="{ overflow: 'auto', height: getWindowHeight(), left: 0 }"
                style=" box-shadow: 2px 2px 2px gainsboro;">
                <a-tree showIcon v-if='treeData.length' :tree-data="treeData" @select="onSelect" :icon="getIcon"
                    :replaceFields="{ title: 'title', key: 'key', children: 'children', isLeaf: 'isLeaf' }"
                    :load-data="onLoadData" :expandedKeys="expandedKeys" :defaultSelectedKeys="selectedKeys"
                    @expand="onExpand">
                    <template slot="custom" slot-scope="item">
                        <!--被选中-->
                        <span v-if="item.selected == true">
                            <!--叶子节点，变蓝无菜单-->
                            <span v-if="item.isLeaf == true"
                                style="color:#0052D9;display:block; float:left;width:100px; background-color: #e1eafa;padding-top:2px;">
                                {{ item.title }}</span>
                            <!--根节点，变蓝有菜单-->
                            <span v-else style=" display:block;float:left;width:120px;background-color: #e1eafa;">
                                <span>{{ item.title }}</span>
                                <span>
                                    <a-dropdown :trigger="['click']">
                                        <a-icon type="ellipsis" @click.stop="showAction(item)"
                                            style="float: right;margin-right:0;line-height:23px;background-color: #e1eafa;color: #0052D9;" />
                                        <a-menu slot="overlay" @click="handleCommand($event, item)">
                                            <a-menu-item key="0">
                                                重新连接
                                            </a-menu-item>
                                            <a-menu-item key="1">
                                                断开连接
                                            </a-menu-item>
                                            <a-menu-item key="2">
                                                编辑
                                            </a-menu-item>
                                            <a-menu-item key="3">
                                                删除
                                            </a-menu-item>
                                        </a-menu>
                                    </a-dropdown>
                                </span>
                            </span>
                        </span>
                        <!--未被选中-->
                        <span v-else>{{ item.title }}</span>
                    </template>
                </a-tree>
            </div>

        </a-layout-sider>
        <!--表格部分-->
        <a-layout style="background: #fff">
            <div class="aside_open" @click="changeCollapse">
                <i v-if="collapsed"><img src="@/assets/icons/redis/u795_2.png"></i>
            </div>
            <!--表格操作按钮-->
            <a-layout-header style="background: #fff; padding: 0">
                <a-button style="margin-left: 2%;background-color:#0052D9;" type="primary" @click="handleAdd"><a-icon
                        type="plus" />创建key</a-button>
                <a-input-search v-model:value="queryParamsKeys.patterndel" placeholder="请输入需要删除的KEY值" @search="onSearch"
                    style="width: 300px; margin-top: 15px;" class="deepblue">
                    <template #enterButton>
                        <a-button :disabled="disable" class="deepblue"><a-icon type="close" />模糊删除</a-button>
                    </template>
                </a-input-search>
                <a-button :disabled="disable" class="deepblue" @click="handleDelete"><a-icon type="close" />删除</a-button>
                <a-button :disabled="disable" class="deepblue" @click="handleDeleteAll"><a-icon
                        type="close" />删除全部</a-button>
                <a-button :disabled="disable" class="deepblue" @click="refreshKeyList"><a-icon type="reload" />刷新</a-button>
                <a-input-search v-model:value="queryParamsKeys.patternfind" placeholder="请输入需要查找的KEY值"
                    style="width: 280px; float: right; margin-top: 15px; margin-right: 15px;" @search="handleQuery" />
            </a-layout-header>
            <!--表格部分-->
            <a-layout-content style="margin: 0 16px">
                <a-card>
                    <a-table :columns="columns"
                        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
                        :dataSource="keysList" :pagination="mypagination" :rowKey="record => record.key" :loading="loading"
                        @change="handleTableChange" style="margin-bottom: 20px;height: getWindowHeight();">

                        <span slot="action" slot-scope="text,record">
                            <a-button type="link" size="small" style="color: #0052D9;"
                                @click="jumpToDetail(record)">查看</a-button>
                            <a-button type="link" size="small" style="color: #0052D9;"
                                @click="handleTtl(record)">过期时间</a-button>
                            <a-button type="link" size="small" style="color: #0052D9;"
                                @click="handleDelete(record)">删除</a-button>
                        </span>
                    </a-table>
                </a-card>
            </a-layout-content>
        </a-layout>
        <!-- 修改ttl -->
        <a-modal :title="title" v-model:visible="open" width="500px">
            <a-form-model ref="form_ttl" :model="formTtl" :rules="rules_ttl">
                <a-form-model-item label="过期时间(秒)" prop="ttl">
                    <a-input v-model:value="formTtl.ttl" placeholder="请输入，-1为无限制"></a-input>
                </a-form-model-item>
            </a-form-model>
            <div slot="footer" class="dialog-footer">
                <a-button type="primary" @click="submitTtl"> 保存</a-button>
                <a-button @click="cancel">取消</a-button>
            </div>
        </a-modal>
        <!-- 修改key名字 -->
        <a-modal :title="title" v-model:visible="open_rename">
            <a-form-model ref="form_keyname" :model="formRename" :rules="rules_rename">
                <a-form-model-item label="Key" prop="newKey">
                    <a-input v-model:value="formRename.newKey" placeholder="请输入新的Key值"></a-input>
                </a-form-model-item>
            </a-form-model>
            <div slot="footer" class="dialog-footer">
                <a-button type="primary" @click="submitKeyName"> 保存</a-button>
                <a-button @click="cancel">取消</a-button>
            </div>
        </a-modal>
        <!-- 新增Key -->
        <a-modal z-index:1001 :title="title" v-model:visible="open_add">
            <a-form-model ref="form_add" :model="formKey" :rules="rules_add">
                <a-form-model-item label="Key" prop="key">
                    <a-input v-model:value="formKey.key" placeholder="请输入"></a-input>
                </a-form-model-item>
                <a-form-model-item label="类型" prop="type">
                    <a-select v-model:value="formKey.type">
                        <a-select-option value="STRING">string</a-select-option>
                        <a-select-option value="LIST">list</a-select-option>
                        <a-select-option value="SET">set</a-select-option>
                        <a-select-option value="ZSET">zset</a-select-option>
                        <a-select-option value="HASH">hash</a-select-option>
                    </a-select>
                </a-form-model-item>
                <a-form-model-item label="Score" prop="score" v-if="formKey.type === 'ZSET'">
                    <a-input v-model:value="formKey.score" placeholder="请输入"></a-input>
                </a-form-model-item>
                <a-form-model-item label="Field" prop="field" v-if="formKey.type === 'HASH'">
                    <a-input type="textarea" rows="4" v-model:value="formKey.field" placeholder="请输入"></a-input>
                </a-form-model-item>
                <a-form-model-item label="Value" prop="value">
                    <a-input type="textarea" rows="4" v-model:value="formKey.value" placeholder="请输入"></a-input>
                </a-form-model-item>
            </a-form-model>
            <div slot="footer" class="dialog-footer">
                <a-button type="primary" @click="submitKeyForm"> 保存</a-button>
                <a-button @click="cancel">取消</a-button>
            </div>
        </a-modal>
        <!-- 左侧 添加创建连接对话框 -->
        <a-modal title="创建连接" v-model:visible="open_addlink" :confirm-loading="confirmLoading" :width="600">
            <a-form-model ref="form_addlink" :model="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }"
                :rules="rules_addlink">
                <a-form-model-item label="连接名称" prop="name">
                    <a-input v-model:value="form.name" placeholder="请输入" />
                </a-form-model-item>
                <a-form-model-item label="IP地址" prop="host">
                    <a-input v-model:value="form.host" placeholder="请输入" />
                </a-form-model-item>
                <a-form-model-item label="端口" prop="port">
                    <a-input v-model:value="form.port" placeholder="请输入" />
                </a-form-model-item>
                <a-form-model-item label="密码" prop="password">
                    <a-input-password v-model:value="form.password" placeholder="请输入" />
                </a-form-model-item>
                <a-form-model-item label="描述" prop="description">
                    <a-textarea allow-clear v-model="form.description" placeholder="请输入"
                        :auto-size="{ minRows: 5, maxRows: 5 }" :maxLength="100" />
                    <span style="position: relative;left: 270px;user-select: none;z-index: 999;top: -50px;">已输入{{
                        queryParams.description.length }}/100</span></a-form-model-item>
            </a-form-model>
            <div slot="footer">
                <a-button type="primary" style="margin-left: 2%;background-color:#0052D9;width: 90px;"
                    @click="submitLinkForm">保存</a-button>
                <a-button @click="testLink" style="width:90px">测试连接</a-button>
                <a-button @click="cancel" style="width:90px">取 消</a-button>
            </div>
        </a-modal>
    </a-layout>
</template>
<script>
import { testLink, getServer, getRedis, getRedisdbs, addServer, updateServer, delServer, reconnectServer, disconnectServer } from "@/api/system/redis";
import { getListKey, addKey, delAllKeys, delKey, renameKey, updateTtl, delVagueKeys } from "@/api/system/keys";

export default {
    name: "redisManagement",
    data() {
        const isValidTtl = (rule, value, callback) => {
            let validttl = /^((-)1|0|[1-9][0-9]*)$/;  // ttl:-1/0/正整数
            if (validttl.test(value)) {
                callback()
            } else {
                callback(new Error("ttl数据不合规"))
            }
        }
        const isValidScore = (rule, value, callback) => {
            let validscore = /^[+-]?([0-9]+([.][0-9]*)?|[.][0-9]+)$/;
            if (validscore.test(value)) {
                callback()
            } else {
                callback(new Error("score数据不合规"))
            }
        }
        return {
            // 表单参数
            form: {},
            codeArray: [],
            treeData: [],
            //创建连接页面
            open_addlink: false,
            // 弹出层open/ttl, open_add/addKey, open_rename/renamekey
            open: false,
            open_add: false,
            open_rename: false,
            // 弹出层标题
            title: "",
            // 遮罩层
            loading: false,
            confirmLoading: false,
            infoList: [],
            collapsed: false,
            selectedKeys: [],
            expandedKeys: [],
            selectedRowKeys: [],
            keysList: [],
            disable: true,
            //树形控件参数
            showIcon: false,
            //pagination分页参数
            mypagination: ({
                // 总数据
                total: 0,
                // 每页条数
                pageSize: 10,
                // 当前页
                current: 1,
                // 显示多少页
                showTotal: (total) => `共 ${total} 条`,
                // 是否开启分页数据条数
                showSizeChanger: true,
                // 分页每页显示条数
                pageSizeOptions: ['10', '20', '50', '100'],
            }),
            // 查询参数
            queryParams: {
                redisId: null,
                name: null,
                host: null,
                port: null,
                password: null,
                description: '',
            },
            queryParamsKeys: {
                pageNum: 1,
                pageSize: 10,
                redisId: null,
                dbId: null,
                key: null,
                pattern: null,
                patterndel: null,
                patternfind: null,
                value: [], // 单个key删除
                sort: 'ascend'
            },
            //表格内容
            columns: [{
                title: 'KEY',
                dataIndex: 'key',
                key: 'key',
                defaultSortOrder: 'ascend',
                sorter: (a, b) => a.key.localeCompare(b.key), // 字符串排序
                sortDirection: ['descend', 'ascend'],
                width: "40%",
                customCell: (record) => {
                    return {
                        style: {
                            color: "#0052D9",
                        },
                        on: {
                            click: () => {
                                this.resetKey()
                                this.formRename.oldKey = record.key
                                this.formRename.newKey = record.key // 输入框内先显示原Key值
                                this.open_rename = true
                                this.title = "重命名"
                            }
                        }
                    }
                }
            },
            {
                title: '类型',
                dataIndex: 'type',
                key: 'type',
                width: "15%",
            },
            {
                title: '大小',
                dataIndex: 'size',
                key: 'size',
                width: "10%",
            },
            {
                title: '过期时间(秒)',
                dataIndex: 'ttl',
                key: 'ttl',
                width: "10%",
                align: 'center',
            },
            {
                title: '操作',
                scopedSlots: { customRender: 'action' },
                width: "25%",
                align: 'center',
            }],
            // key表单参数
            formKey: {
                "redisId": null,
                "dbId": null,
                "type": null,
                "value": null,
                "key": null,
                "score": null,
                "field": null,
            },
            formTtl: {
                "redisId": null,
                "dbId": null,
                "key": null,
                "ttl": null
            },
            formRename: {
                "redisId": null,
                "dbId": null,
                "oldKey": null,
                "newKey": null
            },
            // ttl修改表单校验
            rules_ttl: {
                ttl: [
                    { required: true, message: "过期时间设置不能为空", trigger: "blur" },
                    { validator: isValidTtl, message: "请输入正确的格式，必须为0，正整数或-1", trigger: "blur" }
                ]
            },
            // key新增表单校验
            rules_add: {  // TBC 校验要求
                key: [
                    { required: true, message: "Key设置不能为空", trigger: "blur" },
                ],
                type: [
                    { required: true, message: "类型选择不能为空", trigger: "blur" },
                ],
                score: [
                    { required: true, message: "Score值设置不能为空", trigger: "blur" },
                    { validator: isValidScore, message: "Score为Double类型数据，请输入正确格式", trigger: "blur" }
                ],
                field: [
                    { required: true, message: "Field值设置不能为空", trigger: "blur" },
                ],
                value: [
                    { required: true, message: "Value值设置不能为空", trigger: "blur" },
                ]
            },
            // rename 表单校验
            rules_rename: {
                newKey: [
                    { required: true, message: "新名称设置不能为空", trigger: "blur" },
                ]
            },
            rules_addlink: {
                name: [
                    { required: true, message: "连接名称不能为空", trigger: "blur" },
                ],
                host: [
                    { required: true, message: "IP地址不能为空", trigger: "blur" },
                    { pattern: "^^(((\\d)|([1-9]\\d)|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))\\.){3}((\\d)|([1-9]\\d)|(1\\d{2})|(2[0-4]\\d)|(25[0-5]))$", message: '请输入正确的IP格式,从0.0.0.0到255.255.255.255', trigger: 'blur' }
                ],
                port: [
                    { required: true, message: "端口不能为空", trigger: "blur" },
                    { pattern: /^([1-9]\d{0,3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5])$/, message: '请输入在1-65535的端口', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: "密码不能为空", trigger: "blur" },
                    { min: 6, max: 18, message: "输入长度6-18位", trigger: 'blur' }
                ],
            },
            //树形图标文件路径
            redis_tree_open: require('@/assets/icons/redis/redis-tree-open.png'),
            redis_tree_close: require('@/assets/icons/redis/redis-tree-close.png'),
            redis_leaf: require('@/assets/icons/redis/redis-leaf.png'),
            tree_close: require('@/assets/icons/redis/u90.png'),
        };
    },
    methods: {
        getTree() {
            getRedis().then(response => {
                //拿主干树
                this.treeData = response.data
                //this.treeData = [{ title: 'redis', key: '0', isLeaf: false, scopedSlots: { title: 'custom' } }, { title: 'redis', key: '1', isLeaf: false, scopedSlots: { title: 'custom' } }]
                //this.treeData[1].children = [{ title: 'db0(23)', key: '0-0', isLeaf: true, scopedSlots: { title: 'custom' } }]

            });
        },
        getList() {
            this.loading = true;
            getListKey(this.queryParamsKeys).then(response => {
                this.keysList = response.rows;
                this.mypagination.total = response.total;
                this.loading = false;
                this.disable = false;
                this.selectedRowKeys = [];
            });
        },
        /** table change排序和分页处理 */
        handleTableChange(pagination, filters, sorter) {
            this.queryParamsKeys.pageNum = pagination.current
            this.queryParamsKeys.pageSize = pagination.pageSize
            this.queryParamsKeys.sort = sorter.order
            let { current, pageSize } = pagination
            this.mypagination = Object.assign(this.mypagination, { current, pageSize })
            this.getList()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.resetKey();
            this.open_add = true;
            this.title = "创建Key";
        },
        /** 跳转详情页按钮 */
        jumpToDetail(row) {
            sessionStorage.setItem('pageNum', this.queryParamsKeys.pageNum)
            sessionStorage.setItem('pageSize', this.queryParamsKeys.pageSize)
            this.$router.push({
                name: 'RedisDetail',
                params: {
                    redisId: this.queryParamsKeys.redisId,
                    dbId: this.queryParamsKeys.dbId,
                    key: row.key
                }
            })
        },
        /** 模糊删除按钮 */
        onSearch() {
            this.queryParamsKeys.pattern = this.queryParamsKeys.patterndel
            const query = this.queryParamsKeys
            this.$modal.confirm('删除后无法恢复，是否确认删除"？').then(function() {
                return delVagueKeys(query)
            }).then(() => {
                this.queryParamsKeys.pattern = this.queryParamsKeys.patternfind
                this.queryParamsKeys.patterndel = null
                this.getList()
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            if (row.key) {
                const ids = new Array(row.key)
                this.queryParamsKeys.value = ids
                const query = this.queryParamsKeys  // no directly using this.queryParamsKeys
                this.$modal.confirm('删除后无法恢复，是否确认删除"' + ids + '"？').then(function() {
                    return delKey(query);
                }).then(() => {
                    this.queryParamsKeys.value = [] // 清空value再getlist
                    this.getList()
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => { });
            } else if (this.selectedRowKeys.length !== 0) {
                const multi = this.selectedRowKeys
                this.queryParamsKeys.value = multi
                const query = this.queryParamsKeys
                this.$modal.confirm('删除后无法恢复，是否确认删除"' + multi + '"？').then(function() {
                    return delKey(query);
                }).then(() => {
                    this.queryParamsKeys.value = []
                    this.getList()
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => { });
            } else {
                this.$message.warning('请先选择删除项')
            }
        },
        /** 删除全部*/
        handleDeleteAll() {
            const query = this.queryParamsKeys
            this.$modal.confirm('删除后无法恢复，是否确认删除全部"？').then(function() {
                return delAllKeys(query)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 刷新Key表 */
        refreshKeyList() {
            this.queryParamsKeys.pageNum = 1
            this.queryParamsKeys.pageSize = 10
            this.queryParamsKeys.pattern = null
            this.queryParamsKeys.patternfind = null
            this.queryParamsKeys.patterndel = null
            this.getList()
            this.mypagination.current = 1
            this.mypagination.pageSize = 10
        },
        /** 搜索操作 */
        handleQuery() {
            this.mypagination.current = 1
            this.mypagination.pageSize = 10
            this.queryParamsKeys.pageNum = 1
            this.queryParamsKeys.pageSize = 10
            this.queryParamsKeys.pattern = this.queryParamsKeys.patternfind
            this.getList()
        },
        /** 创建连接提交按钮 */
        submitLinkForm() {
            this.$refs["form_addlink"].validate(valid => {
                if (valid) {
                    if (this.form.redisId != null || this.form.id != null) {
                        updateServer(this.form).then(response => {
                            var redisid = this.form.id
                            this.$modal.msgSuccess("修改成功");
                            this.open_addlink = false;
                            for (var i = 0; i < this.treeData.length; i++) {
                                if (redisid == this.treeData[i].key) {
                                    this.treeData[i].title = this.form.name;
                                }
                            }
                        })
                    }
                    else {
                        addServer(this.form).then(response => {
                            this.open_addlink = false;
                            this.$modal.msgSuccess("新增成功");
                            let obj = { "title": this.form.name, "key": response.data, "isLeaf": false, scopedSlots: { title: 'custom' } }
                            this.treeData.push(obj)
                            this.getTree()
                        })
                    }
                }
            });
        },
        // key提交按钮
        submitKeyForm() {
            this.$refs["form_add"].validate(valid => {
                if (valid) {
                    let obj = {
                        redisId: this.queryParamsKeys.redisId,
                        dbId: this.queryParamsKeys.dbId,
                        type: this.formKey.type,
                        key: this.formKey.key,
                        value: [],
                    }
                    if (this.formKey.score) {
                        // console.log("It's Zset")
                        obj.value[0] = this.formKey.value
                        obj.value[1] = this.formKey.score
                    } else if (this.formKey.field) {
                        // console.log("it's Hash")
                        obj.value[0] = this.formKey.field
                        obj.value[1] = this.formKey.value
                    } else {
                        // console.log("It's regular")
                        obj.value = this.formKey.value
                    }
                    addKey(obj).then(response => {
                        this.$modal.msgSuccess("新增成功")
                        this.resetKey()
                        this.open_add = false;
                        this.getList();
                    })
                }
            })
        },
        // 提交RenameKey 
        submitKeyName() {
            this.$refs["form_keyname"].validate(valid => {
                if (valid) {
                    if (this.formRename.oldKey !== this.formRename.newKey) {
                        this.formRename.redisId = this.queryParamsKeys.redisId
                        this.formRename.dbId = this.queryParamsKeys.dbId
                        renameKey(this.formRename).then(response => {
                            this.$modal.msgSuccess("重命名成功")
                            this.open_rename = false;
                            this.getList();
                        })
                    } else {
                        this.$message.warning('请输入新的名字')
                    }
                }
            })
        },
        // 提交ttl
        submitTtl() {
            this.formTtl.redisId = this.queryParamsKeys.redisId
            this.formTtl.dbId = this.queryParamsKeys.dbId
            this.$refs["form_ttl"].validate(valid => {
                if (valid) {
                    updateTtl(this.formTtl).then(response => {
                        this.$modal.msgSuccess("过期时间修改成功")
                        this.open = false;
                        this.getList();
                    })
                }
            })
            // var raw = JSON.stringify(this.formTtl)
        },
        // 修改ttl按钮
        handleTtl(row) {
            this.resetKey()
            this.formTtl.key = row.key
            this.formTtl.ttl = row.ttl
            this.open = true
            this.title = "过期时间"
        },
        // 取消按钮
        cancel() {
            this.open_addlink = false;
            this.open = false;
            this.open_add = false,
                this.open_rename = false,
                this.resetKey()
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                name: null,
                redisId: null,
                id: null,
                host: null,
                port: null,
                password: null,
                description: null,
            }
            this.resetForm("form");
        },
        // 新增 重命名 设置ttl
        resetKey() {
            this.formKey = {
                redisId: null,
                dbId: null,
                type: null,
                value: null,
                key: null,
                score: null,
                field: null,
            }
            this.formRename = {
                redisId: null,
                dbId: null,
                oldKey: null,
                newKey: null
            }
            this.formTtl = {
                redisId: null,
                dbId: null,
                key: null,
                ttl: null,
            }
            this.resetForm("formKey")
            this.resetForm("formRename")
        },
        /**根据当前窗口高度动态设置**/
        getWindowHeight() {
            return (window.innerHeight - 40) + 'px'
        },
        // 多选框选数据
        onSelectChange(selectedRowKeys) {
            // console.log('selectedRowKeys changed: ', selectedRowKeys)
            this.selectedRowKeys = selectedRowKeys
        },
        //树形控件选择
        onSelect(selectedKeys, item) {
            this.selectedKeys = selectedKeys
            sessionStorage.setItem('selectedKeys', this.selectedKeys)
            if (item.node.dataRef.isLeaf == true) {
                var dbid = item.node.dataRef.key;
                var area = dbid.split("-");
                //redisId改成aaaa拿除最后一个-前面的，dbid改成拿最后一个-后面的
                this.queryParamsKeys.dbId = area[area.length - 1];
                area = area.slice(0, -1)
                this.queryParamsKeys.redisId = area.join('-');
                console.log(this.queryParamsKeys.dbId, this.queryParamsKeys.redisId)
                this.queryParamsKeys.patternfind = null
                this.mypagination.current = 1
                this.mypagination.pageSize = 10
                this.queryParamsKeys.pageNum = 1
                this.queryParamsKeys.pageSize = 10
                this.queryParamsKeys.pattern = null
                this.getList()
                // console.log(this.queryParamsKeys)
            }
        },
        onExpand(keys) {
            // expandedKeys(.sync)	（受控）展开指定的树节点
            this.expandedKeys = keys
            sessionStorage.setItem('expandedKeys', this.expandedKeys)
        },
        //改a-directory-tree图标
        getIcon(props) {
            if (!props.isLeaf) {
                if (props.dataRef.children) {
                    if (props.selected) {
                        return <i><img style='width:24px; height:24px;vertical-align: baseline;background-color: #e1eafa;' src={this.redis_tree_open} /></i>;
                    }
                    else {
                        return <i><img style='width:24px; height:24px;vertical-align: baseline;' src={this.redis_tree_open} /></i>;
                    }
                }
                else {
                    if (props.selected) {
                        return <i><img style='width:24px; height:24px;vertical-align: baseline;background-color: #e1eafa;' src={this.redis_tree_close} /></i>;
                    }
                    else {
                        return <i><img style='width:24px; height:24px;vertical-align: baseline;' src={this.redis_tree_close} /></i>;
                    }
                }
            }
            else {
                if (props.selected) {
                    return <i><img style='width:24px; height:24px;vertical-align: baseline;background-color: #e1eafa;' src={this.redis_leaf} /></i>;
                }
                else {
                    return <i><img style='width:24px; height:24px;vertical-align: baseline;' src={this.redis_leaf} /></i>;
                }
            }
        },
        createLink() {
            this.reset()
            this.open_addlink = true;
        },
        changeCollapse() {
            this.collapsed = !this.collapsed;
        },
        showAction(item) {
            //用@click.stop保留外侧的选中状态
        },
        testLink() {
            testLink(this.form).then(response => {
                if (response.msg == "测试连接失败") {
                    this.$modal.msgError("测试连接失败")
                }
                else {
                    this.$modal.msgSuccess("测试连接成功")
                }
            })
        },
        handleCommand(command, item) {
            command = command.key
            if (command == "0") {
                getRedisdbs(item.dataRef.key).then(response => {
                    // console.log(item)
                    item.dataRef["children"] = response.data
                    this.expandedKeys.push(item.key)
                    sessionStorage.setItem('expandedKeys', this.expandedKeys)
                    //使用下面这行数据就会更新了
                    this.treeData = [...this.treeData];
                })
                this.$modal.msgSuccess("已重新连接");

            }
            else if (command == "1") {
                item.dataRef["children"] = null;
                var index = this.expandedKeys.indexOf(item.key);
                if (index > -1) {
                    this.expandedKeys.splice(index, 1)
                }
                sessionStorage.setItem('expandedKeys', this.expandedKeys)
                this.treeData = [...this.treeData];
                this.$modal.msgSuccess("已断开连接");

            }
            else if (command == "2") {
                console.log(item.key)
                getServer(item.key).then(response => {
                    console.log(response.data)
                    this.form = response.data;
                    this.open_addlink = true;
                    this.title = "编辑连接";
                });
            }
            else if (command == "3") {
                this.$modal.confirm('是否确认删除').then(function() {
                    return delServer(item.key);
                }).then(() => {
                    //刷新树的函数，后面增加
                    this.treeData = this.treeData.filter((val) => val.key != item.key)
                    this.$modal.msgSuccess("删除成功");
                }).catch(() => { });
            }
        },
        onLoadData(treeNode) {
            this.queryParamsKeys.redisId = treeNode.dataRef.key
            return new Promise(resolve => {
                if (treeNode.dataRef.children != null) {
                    resolve();
                    return;
                }
                else {
                    getRedisdbs(treeNode.dataRef.key).then(response => {
                        treeNode.dataRef["children"] = response.data
                        //使用下面这行数据就会更新了
                        this.treeData = [...this.treeData];
                        resolve()
                    })
                }
            })
        },

    },
    beforeRouteEnter(to, from, next) {
        // console.log(from)
        if (from.name !== 'RedisDetail') {
            sessionStorage.clear()
            // console.log("SessionStorage has been cleared!")
            next(vm => { })
        } else {
            next(vm => {
                vm.mypagination.current = parseInt(sessionStorage.getItem('pageNum'))
                vm.mypagination.pageSize = parseInt(sessionStorage.getItem('pageSize'))
            })
        }

    },
    created() {
        this.getTree();
        this.selectedRowKeys = [];
        if (sessionStorage.getItem('expandedKeys')) {
            this.expandedKeys = sessionStorage.getItem('expandedKeys').split(',')
            if (this.selectedKeys != null) {
                this.selectedKeys = sessionStorage.getItem('selectedKeys').split(',')
                let temp_selected = sessionStorage.getItem('selectedKeys');
                let area = temp_selected.split("-");
                this.queryParamsKeys.dbId = area[area.length - 1];
                area = area.slice(0, -1)
                this.queryParamsKeys.redisId = area.join('-');
                this.queryParamsKeys.pageNum = parseInt(sessionStorage.getItem('pageNum'))
                this.queryParamsKeys.pageSize = parseInt(sessionStorage.getItem('pageSize'))
                this.getList()
            }
        }

    },
    computed: {
        hasSelected() {
            return this.selectedRowKeys.length > 0;
        },
    },

};
</script>

<style scoped>
::v-deep .ant-table-thead>tr>th,
.ant-table-tbody>tr>td {
    padding: 8px 8px;
    overflow-wrap: break-word;
}

::v-deep .ant-table-tbody .ant-table-row td {
    padding-top: 8px;
    padding-bottom: 8px;
}


::v-deep .ant-tree-switcher_close {
    background: url('~@/assets/icons/redis/u96.png') no-repeat 5px !important;
}

::v-deep .ant-tree-switcher_open {
    background: url('~@/assets/icons/redis/u90.png') no-repeat 5px !important;
}

::v-deep .ant-tree-switcher_open>i {
    display: none !important;
}

::v-deep .ant-tree-switcher_close>i {
    display: none !important;
}


::v-deep .ant-tree-treenode-selected span:nth-child(2) {
    background-color: white;

}

::v-deep .ant-modal-header {
    padding: 10px 15px;
    height: 40px;
}

::v-deep .ant-modal-title {
    font-size: 12px;
}

::v-deep .ant-form-item {
    margin-bottom: 8px;
    line-height: 1;
}

.aside_open_close {
    position: absolute;
    right: 0;
    top: 50%;
    width: 16px;
    line-height: 40px;
    color: #fff;
    margin-right: 40px;
    background-color: #fff;
    font-size: 20px;
    z-index: 1000;
    cursor: pointer;
    transform: perspective(10px) rotateX(0deg) rotateY(-18deg) translateZ(0);
}

.header {
    height: 30px;
}

.header-left {
    padding-top: 5px;
    float: left;
    margin-bottom: 2px;
}

.header-button {
    height: 25px;
    float: left;
    width: 15px;
    padding-top: 5px;
    margin-left: 115px;
    color: #0052D9;
}

.deepblue {
    margin-left: 2%;
    color: #0052D9;
    background-color: white;
    border-color: #0052D9;
}

.deepblue:hover {
    color: #5c8bd7;
    background-color: white;
    border-color: #5c8bd7;
}

::v-deep.ant-layout-sider {
    flex: 0 0 240px !important;
    max-width: 240px !important;
    min-width: 240px !important;
    width: 240px !important;
    height: 555px;
}

::v-deep.ant-layout-sider-collapsed {
    flex: 0 0 70px !important;
    max-width: 70px !important;
    min-width: 70px !important;
    width: 70px !important;
}

::v-deep.ant-tree li .ant-tree-node-content-wrapper:hover {
    background-color: #fff;
}


::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: rgba(0, 0, 0, 0.1);
    -webkit-box-shadow: inset 0 0 6px #ececec;
}

::-webkit-scrollbar-track {
    background: #fff
}

.aside_close {
    position: absolute;
    right: 29px;
    top: 50%;
    width: 16px;
    height: 60px;
    line-height: 60px;
    color: #fff;
    background-color: #fff;
    border-radius: 0 6px 6px 0;
    font-size: 20px;
    z-index: 1000;
    cursor: pointer;
}

.aside_open {
    position: absolute;
    left: 0;
    top: 45%;
    width: 16px;
    height: 60px;
    line-height: 60px;
    color: #fff;
    background-color: #fff;
    border-radius: 0 6px 6px 0;
    font-size: 20px;
    z-index: 1000;
    cursor: pointer;
}

.aside_open:hover {
    transform: scale(1.05);
}

.aside_close:hover {
    transform: scale(1.05);
}

::v-deep .ant-tree-iconEle {
    float: left;
}
</style>
